import type { Project, ProjectGroup, ApiResponse, ProjectFormData, GroupFormData } from '@/types';

const BASE_URL = '/plugin.nohost/cgi-bin/api';

// 通用请求函数
async function request<T>(url: string, options: RequestInit = {}): Promise<ApiResponse<T>> {
  const response = await fetch(`${BASE_URL}${url}`, {
    headers: {
      'Content-Type': 'application/json',
      ...options.headers,
    },
    ...options,
  });

  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }

  return response.json();
}

// 项目相关API
export const projectApi = {
  // 获取所有项目
  async getAll(): Promise<ApiResponse<{ projects: Project[], projectGroups: ProjectGroup[] }>> {
    return request<{ projects: Project[], projectGroups: ProjectGroup[] }>('/project');
  },

  // 获取单个项目
  async getById(id: string): Promise<ApiResponse<Project>> {
    return request<Project>(`/project/${id}`);
  },

  // 创建项目
  async create(data: ProjectFormData): Promise<ApiResponse<Project>> {
    return request<Project>('/project', {
      method: 'POST',
      body: JSON.stringify(data),
    });
  },

  // 更新项目
  async update(id: string, data: Partial<ProjectFormData>): Promise<ApiResponse<Project>> {
    return request<Project>(`/project/${id}`, {
      method: 'PUT',
      body: JSON.stringify(data),
    });
  },

  // 删除项目
  async delete(id: string): Promise<ApiResponse<void>> {
    return request<void>(`/project/${id}`, {
      method: 'DELETE',
    });
  },

  
  // 更新规则
  async updateRules(rules: string[]): Promise<ApiResponse<any>> {
    return request<any>(`/activate/rules`, {
      method: 'POST',
      body: JSON.stringify({ rules }),
    });
  },

  // 激活环境
  async activateEnvironment(rules: string[]): Promise<ApiResponse<any>> {
    return request<any>(`/cgi-bin/api/activate/rules`, {
      method: 'POST',
      body: JSON.stringify({ rules }),
    });
  },

  // 取消激活环境
  async deactivateEnvironment(projectId: string, envId: string): Promise<ApiResponse<any>> {
    return request<any>(`/project/${projectId}/environment/${envId}/deactivate`, {
      method: 'POST',
    });
  },

  // 强制刷新Whistle规则 (实时同步优化)
  async forceRefreshRules(): Promise<ApiResponse<void>> {
    return request<void>('/whistle/force-refresh', {
      method: 'POST',
    });
  },

  // 重新加载Whistle规则
  async reloadRules(): Promise<ApiResponse<void>> {
    return request<void>('/whistle/reload', {
      method: 'POST',
    });
  },
};

// 分组相关API
export const groupApi = {
  // 获取所有分组
  async getAll(): Promise<ApiResponse<ProjectGroup[]>> {
    return request<ProjectGroup[]>('/group');
  },

  // 获取单个分组
  async getById(id: string): Promise<ApiResponse<ProjectGroup>> {
    return request<ProjectGroup>(`/group/${id}`);
  },

  // 创建分组
  async create(data: GroupFormData): Promise<ApiResponse<ProjectGroup>> {
    return request<ProjectGroup>('/group', {
      method: 'POST',
      body: JSON.stringify(data),
    });
  },

  // 更新分组
  async update(id: string, data: GroupFormData): Promise<ApiResponse<ProjectGroup>> {
    return request<ProjectGroup>(`/group/${id}`, {
      method: 'PUT',
      body: JSON.stringify(data),
    });
  },

  // 删除分组
  async delete(id: string): Promise<ApiResponse<void>> {
    return request<void>(`/group/${id}`, {
      method: 'DELETE',
    });
  },
};
